//task_doorInstallation.js
const util = require("../../utils/util.js");

const app = getApp()

Page({
  data: {
    order_id: '',
    // 选中的任务类型
    selectedTask_type: "上门安装",
    // 任务时间
    taskTime: "",
    surImages: [],
    surveyReport: {},
    index: 0,
    // 存放本地图片路径
    tempFilePaths: [],
    // 存放图片上传路径
    imagesUpload: [],
    // 安装费用
    installPrice: "",
    // 安装总额
    totalPrice: "",
    // 备注信息
    memoInfo: "",
    // 房间物料数组
    house_materiel_array: [],
    // 任务信息
    taskObject: {}
  },
  // 页面出现
  onShow: function () {
    console.log("11111+adminUserViewId:" + app.globalData.adminUserViewId);
    console.log("111111+token:" + app.globalData.token);
    if (app.globalData.adminUserViewId === undefined || app.globalData.token === undefined || app.globalData.adminUserViewId === "" || app.globalData.token === "") {
      wx.redirectTo({ url: '/pages/login/login' });
      console.log("未登录，调取登录页面");
    } else {
      console.log("已登录，请求数据");
      // 已登录，请求数据
      if (this.data.refreshLish == "true") {
        console.log("需要重新刷新数据~~~~");
        this.refreshNewData();
        this.setData({
          refreshLish: "false"
        });
      }

    }
    console.log("页面出现.");
  },
  onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.setData({
      order_id: options.id,
      taskTime: options.time,
      taskAddress: options.address,
      installPrice: options.installFee,
      totalPrice: options.installFee
    })

    console.log("上门安装：id=" + this.data.order_id + 'address=' + this.data.taskAddress + 'time=' + this.data.taskTime);

    this.refreshNewData();

    this.$wuxToast = app.wux(this).$wuxToast
  },
  // 查看勘测表
  showKanceImage: function () {
    var that = this;
    wx.previewImage({
      current: that.data.surveyReport.url, // 当前显示图片的http链接
      urls: [that.data.surveyReport.url] // 需要预览的图片http链接列表
    })
  },
  // 安装位置图片查看
  showImage: function (event) {
    var index = event.currentTarget.dataset.index;
    var that = this;
    var currentUrl = that.data.surImages[index];

    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: that.data.surImages // 需要预览的图片http链接列表
    })
  },
  // 安装费用
  inputInstallPrice: function (e) {
    this.setData({
      installPrice: e.detail.value
    })
  },
  // 收费总额
  inputTotalPrice: function (e) {
    this.setData({
      totalPrice: e.detail.value
    })
  },
  // 备注信息
  inputMemoInfo: function (e) {
    this.setData({
      memoInfo: e.detail.value
    })
  },
  // 物料价格输入框
  materiel_bindinput: function (e) {
    var value = e.detail.value;
    var index = e.currentTarget.dataset.index;
    var houseIndex = e.currentTarget.dataset.houseindex;
    console.log("物料信息：index ===" + index + "; houseIndex==" + houseIndex);
    var newTotalPrice = this.data.totalPrice;
    var oldMaterilPrice = this.data.house_materiel_array[houseIndex].materielArray[index].materielPrice;

    if (oldMaterilPrice == undefined) {
      oldMaterilPrice = 0;
    }
    var oldMaterilCount = this.data.house_materiel_array[houseIndex].materielArray[index].materielCount;
    var oldMaterielTotalPrice = oldMaterilPrice * oldMaterilCount;
    this.data.house_materiel_array[houseIndex].materielArray[index].materielPrice = value;

    // 修改房间数组的全局变量
    this.setData({
      houe_materiel_array: this.data.house_materiel_array
    });

    var newMaterielTotalPrice = this.data.house_materiel_array[houseIndex].materielArray[index].materielPrice * this.data.house_materiel_array[houseIndex].materielArray[index].materielCount;
    newTotalPrice = newTotalPrice - oldMaterielTotalPrice + newMaterielTotalPrice;
    this.setData({
      totalPrice: newTotalPrice
    });

  },

  // 扫描二维码
  scodeTap: function (e) {
    var index = e.currentTarget.dataset.index;
    console.log("index:" + index);
    const that = this;
    wx.scanCode({
      success: (res) => {
        var textStr = res.result;
        console.log("条形码:" + res.result + "path===" + res.path);

        this.data.house_materiel_array[index].machineNo = textStr;
        // 修改全局变量
        that.setData({
          house_materiel_array: that.data.house_materiel_array
        })
      }
    })
  },
  // 输入机器ID
  machineNoBindinput: function (e) {
    var index = e.currentTarget.dataset.index;
    var value = e.detail.value;
    var that = this;
    this.data.house_materiel_array[index].machineNo = value;
    // 修改全局变量
    this.setData({
      house_materiel_array: that.data.house_materiel_array
    });
  },
  // 查看上传图片
  uploadImageShowAction: function (event) {
    var index = event.currentTarget.dataset.index;
    var that = this;
    var currentUrl = that.data.imagesUpload[index];

    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: that.data.imagesUpload // 需要预览的图片http链接列表
    })
  },
  // 选择图片
  chooseimage: function () {
    var _this = this;
    var imagePaths = this.data.tempFilePaths;
    var uploadImagePaths = this.data.imagesUpload;

    wx.chooseImage({
      count: 9, // 默认9  
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        // 新选择图片的本地路径
        var filePathsArray = res.tempFilePaths;
        wx.showToast({
          title: '上传中...',
          icon: 'loading',
          mask: true,
          duration: 20000000
        });

        filePathsArray.forEach(function (item, index) {
          wx.uploadFile({
            url: app.globalData.BaseURL + '/fileUpload/image',
            filePath: item,
            name: 'file',
            success: function (res) {
              var state = JSON.parse(res.data).state;
              if (state == "success") {
                var url = JSON.parse(res.data).url;
                // 存放图片上传路径数组加1️
                uploadImagePaths.push(url);
                _this.setData({
                  imagesUpload: uploadImagePaths
                })
                // 存放本地图片路径数组加1️
                imagePaths.push(item);
                _this.setData({
                  tempFilePaths: imagePaths
                })
                if (index == filePathsArray.length - 1) {
                  wx.hideToast();
                }
              } else {
                wx.hideToast();
                _this.$wuxToast.show({
                  type: 'text',
                  timer: 1500,
                  color: '#fff',
                  text: '图片上传失败，请重新选择',
                  success: () => console.log('文本内容')
                })
              }
              console.log("上传成功");
              console.log(JSON.parse(res.data));
              console.log(JSON.parse(res.data).url);
            },
            fail: function (res) {
              wx.hideToast();
              console.log("上传失败：" + res.data);
              _this.$wuxToast.show({
                type: 'text',
                timer: 1500,
                color: '#fff',
                text: '图片上传失败，请重新选择',
                success: () => console.log('文本内容')
              })
            }, complete: function () {
            }
          });
        });

      }
    })
  },
  submitInfoFunc: function () {    
    var that = this;
    var isNotEmpty = 0;  // 0：为空；1：不为空
    var materielCount = 0;
    var materielLength = this.data.house_materiel_array.length;
    this.data.house_materiel_array.forEach(function (e) {

      var materielItemArray = e.materielArray;
      var machineNoStr = e.machineNo;
      if (machineNoStr == "" || machineNoStr == undefined) {
        that.$wuxToast.show({
          type: 'text',
          timer: 1000,
          color: '#fff',
          text: '机器ID不能为空，请检查',
          success: () => console.log('机器ID不能为空，请检查')
        })
      } else if (machineNoStr.length != 16) {
        that.$wuxToast.show({
          type: 'text',
          timer: 1000,
          color: '#fff',
          text: '机器ID为16位，请检查',
          success: () => console.log('机器ID为16位，请检查')
        })
        return;
      } else {
        materielCount++;
        console.log("数组遍历到第几个了：" + materielCount);
        var materielItemCount = 0;
        materielItemArray.forEach(function (e) {
          var materielPriceStr = e.materielPrice;
          if (materielPriceStr == "" || materielPriceStr == undefined) {
            that.$wuxToast.show({
              type: 'text',
              timer: 1000,
              color: '#fff',
              text: '物料金额不能为空，请检查',
              success: () => console.log('网络错误，请稍后重试。')
            })
            return;
          } else {
            materielItemCount++;
            console.log("子数组遍历到第几个了：" + materielCount);
            if (materielCount == materielLength && materielItemCount == that.data.house_materiel_array[materielLength - 1].materielArray.length) {
              isNotEmpty = 1;
            }
          }
        });
      }
    });

    if (isNotEmpty == 1) {
      // 总金额
      var totalPriceStr = this.data.totalPrice;
      if (totalPriceStr == "" || totalPriceStr == undefined) {
        that.$wuxToast.show({
          type: 'text',
          timer: 1000,
          color: '#fff',
          text: '收费总金额不能为空，请检查',
          success: () => console.log('收费总金额不能为空，请检查')
        })
        return;
      }

      // 安装费用
      var installPriceStr = this.data.installPrice;
      if (installPriceStr == "" || installPriceStr == undefined) {
        that.$wuxToast.show({
          type: 'text',
          timer: 1000,
          color: '#fff',
          text: '安装费用不能为空，请检查',
          success: () => console.log('安装费用不能为空，请检查')
        })
        return;
      }

      var installPriceStr = this.data.installPrice;
      var memoInfoStr = this.data.memoInfo;
      var installImagesArr = this.data.imagesUpload;
      var house_materiel_Data = this.data.house_materiel_array;
      var house_materiel_Str = JSON.stringify(house_materiel_Data);
      //加载提示框
      util.showLoading();

      var pages = getCurrentPages()
      var prevPage = pages[pages.length - 2]  //上一个页面

      var urlString = app.globalData.BaseURL + '/api/task/addInstallReport';
      var dataSource = util.json2Form({
        taskId: that.data.order_id,
        materielList: house_materiel_Str,
        installPrice: installPriceStr,
        totalPrice: totalPriceStr,
        userReport: memoInfoStr,
        installImages: installImagesArr
      });

      wx.request({
        method: "POST",
        url: urlString,
        data: dataSource,
        header: {
          "Content-Type": "application/x-www-form-urlencoded",
          'adminUserViewId': app.globalData.adminUserViewId,
          'token': app.globalData.token
        },
        success: function (res) {
          util.hideToast();
          console.log("data=====" + res.data);
          var code = res.data.code;
          console.log("code=====" + code);
          // code = 300;
          if (code === 200) {
            that.$wuxToast.show({
              type: 'text',
              timer: 1000,
              color: '#fff',
              text: '上传成功',
              success: () => console.log('提交成功')
            });
            // 更改前一页面列表页的refreshLish属性，让其出现时刷新页面
            prevPage.setData({
              refreshLish: "true"
            });
            setTimeout(function () {
              wx.navigateBack({});
            }, 1000);
          } else {
            that.$wuxToast.show({
              type: 'text',
              timer: 1000,
              color: '#fff',
              text: res.data.msg,
              success: () => console.log('上传失败，请重新提交。')
            });
          }
        },
        fail: function () {
          that.$wuxToast.show({
            type: 'text',
            timer: 1000,
            color: '#fff',
            text: '网络错误，请稍后重试。',
            success: () => console.log('网络错误，请稍后重试。')
          })
        }, complete: function () {
          util.hideToast();
        }
      })
    }
  },// 任务失败跳转
  taskFailedAction: function () {
    var that = this;
    wx.navigateTo({
      url: '/pages/task_failed/task_failed' + '?id=' + that.data.order_id + '&time=' + that.data.taskTime + '&address=' + that.data.taskAddress + '&task_type=' + that.data.selectedTask_type
    })
  },
  //刷新数据
  refreshNewData: function () {
    //加载提示框
    util.showLoading();
    var that = this;
    var urlStr = '/api/task/' + this.data.order_id;
    var parameters = "";

    util.request(urlStr, parameters, function (res) {
      console.log("data===" + res.data);
      util.hideToast();
      var materialPreStr = res.data.data.materielReqment;
      var surveyReportStr = res.data.data.surveyReport;
      var surImagesStr = res.data.data.surImages;
      console.log("图片数组：" + surImagesStr);
      console.log("安装信息：" + surveyReportStr);

      that.setData({
        house_materiel_array: materialPreStr,
        surveyReport: surveyReportStr,
        surImages: surImagesStr,
        taskObject: res.data.data.task
      });

      var startTime = res.data.data.task.startTime;
      if (startTime == "" || startTime == undefined) {
        // 未开始任务，提示先开始任务
        wx.showModal({
          title: '该任务暂未开始',
          content: '请返回首页开始任务，再提交任务信息',
          cancelText: '暂不开始',
          confirmText:'立即返回',
          success: function (res) {
            if (res.confirm) {
              console.log("确认返回首页");
              wx.navigateBack({})
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })        
      }
    })
  }, complete: function () {
    util.hideToast();
  }

})